package service

import (
	"context"
	"iris-wms/apps/admin/web/dto/din"
	"iris-wms/apps/admin/web/dto/dout"
	"iris-wms/common/pkg/db"
	"iris-wms/common/pkg/db/dao"

	"gorm.io/gen"
)

var _ WmsHistoryService = (*wmsHistoryService)(nil)

type WmsHistoryService interface {
	GetInAndOutHistory(din.WmsHistoryTableIn) ([]*dout.WmsInventoryOut, int64, error)
	// GetDeliverHistory()
}

func NewWmsHistoryService() *wmsHistoryService {
	return &wmsHistoryService{}
}

type wmsHistoryService struct{}

func (impl *wmsHistoryService) GetInAndOutHistory(in din.WmsHistoryTableIn) (rows []*dout.WmsInventoryOut, total int64, err error) {
	dao.SetDefault(db.GDB1)
	q := dao.WmsInventoryOut
	do := q.WithContext(context.Background())

	condList := make([]gen.Condition, 0)
	if in.IoType > 0 {
		var billIdList = make([]uint, 0)
		if err = dao.WmsBillOut.UnderlyingDB().
			Raw("SELECT id FROM wms_bill WHERE io_type=?", in.IoType).
			Scan(&billIdList).Error; err != nil {
			return
		}
		condList = append(condList, q.BillId.In(billIdList...))
	}
	if in.Wid > 0 {
		condList = append(condList, q.Wid.Eq(in.Wid))
	}
	if in.GoodsId > 0 {
		condList = append(condList, q.GoodsId.Eq(in.GoodsId))
	}

	if len(condList) > 0 {
		do = do.Where(condList...)
	}
	rows, total, err = do.
		Preload(q.Bill.IoTypeDict).
		Preload(q.Goods.Cate).
		Preload(q.Warehouse).
		Order(q.CreatedAt.Desc()).
		FindByPage(in.Offset(), in.PageSize)
	return
}
